const joi = require('joi');
const dbQuery = require('../model/db');
const {
	sendError,
	sendSuccess
} = require('../utils/sendFunction');

// 验证规则
const schemaAddNewsType = joi.object({
	name: joi.string().required().error(new Error('name不符合验证规则')),
	create_time: joi.string().required().error(new Error('create_time不符合验证规则')),
})

const schemaEditNewsType = joi.object({
	name: joi.string().required().error(new Error('name不符合验证规则')),
	id: joi.number().required().error(new Error('id不符合验证规则'))
})

const schemaDeleteNewsTypeAndGet = joi.object({
	id: joi.number().required().error(new Error('id不符合验证规则'))
})

const schemaDeleteNewsAndGet = joi.object({
	id: joi.number().required().error(new Error('id不符合验证规则'))
})

// title content picfile create_time newsTypeId
const schemaAddNews = joi.object({
	title: joi.string().required().error(new Error('title不符合验证规则')),
	content: joi.string().required().error(new Error('content不符合验证规则')),
	create_time: joi.string().required().error(new Error('create_time不符合验证规则')),
	newsTypeId: joi.number().required().error(new Error('newsTypeId不符合验证规则'))
})

// id title picfile newsTypeId
const schemaEditNews = joi.object({
	title: joi.string().required().error(new Error('title不符合验证规则')),
	newsTypeId: joi.number().required().error(new Error('newsTypeId不符合验证规则')),
	id: joi.number().required().error(new Error('id不符合验证规则'))
})

// name create_time
const addNewsType = async function (req, res, next) {
	let {
		name,
		create_time
	} = req.body;

	if (!name || !create_time) {
		sendError(res, 200, '新闻类型名称或创建时间不能为空!');
		return;
	}

	try {
		await schemaAddNewsType.validateAsync({
			name,
			create_time
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'select * from newstype where newstype_name=?'
	let result = await dbQuery(sqlStr, name);
	if (result.length !== 0) {
		sendError(res, 200, '新闻类型名称被占用，请更换其他新闻类型名称!');
		return;
	}

	let sqlStr1 = 'insert into newstype (newstype_name,newstype_create_time) values (?,?)';
	let result1 = await dbQuery(sqlStr1, [name, create_time]);
	if (result1.affectedRows == 1) {
		sendSuccess(res, '添加新闻类型成功!');
	} else {
		sendError(res, 500, '添加新闻类型失败，请稍后再试!')
	}
}

// id name(new)
const editNewsType = async function (req, res, next) {
	let {
		id,
		name
	} = req.body;

	if (!name || !id) {
		sendError(res, 200, '新闻类型名称或id不能为空!');
		return;
	}

	try {
		await schemaEditNewsType.validateAsync({
			name,
			id
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'select * from newstype where newstype_name=? and newstypeid!=?'
	let result = await dbQuery(sqlStr, [name, id]);
	if (result.length !== 0) {
		sendError(res, 200, '新闻类型名称已被占用，请更换后重试!');
		return;
	}

	let sqlStr1 = 'update newstype set newstype_name=? where newstypeid=?'
	let result1 = await dbQuery(sqlStr1, [name, id]);
	if (result1.affectedRows == 1) {
		sendSuccess(res, '修改新闻类型成功!');
	} else {
		sendError(res, 500, '修改新闻类型失败，请稍后再试!')
	}
}

const deleteNewsType = async function (req, res, next) {
	let {
		id
	} = req.query;

	if (!id) {
		sendError(res, 200, 'id不能为空!');
		return;
	}

	try {
		await schemaDeleteNewsTypeAndGet.validateAsync({
			id
		})
	} catch (error) {
		next(error);
		return;
	}

	// 如果该新闻类型有新闻
	let sqlStr = 'select * from news where newstype_id=?'
	let result = await dbQuery(sqlStr, [id]);
	if (result.length !== 0) {
		sendError(res, 200, '删除新闻类型失败，该新闻类型中有新闻!')
		return;
	}

	let sqlStr1 = 'delete from newstype where newstypeid=?'
	let result1 = await dbQuery(sqlStr1, [id]);
	if (result1.affectedRows == 1) {
		sendSuccess(res, '删除新闻类型成功!');
	} else {
		sendError(res, 500, '删除新闻类型失败，请稍后再试!')
	}
}

const getNewsType = async function (req, res, next) {
	let sqlStr = 'select * from newstype';
	let result = await dbQuery(sqlStr);
	if (result.length >= 0) {
		sendSuccess(res, '获取新闻类型成功!', {
			data: result
		})
	} else {
		sendError(res, 500, '获取新闻类型失败，请稍后再试!')
	}
}

const getNewsTypeById = async function (req, res, next) {
	let {
		id
	} = req.query;

	if (!id) {
		sendError(res, 200, 'id不能为空！');
		return;
	}

	try {
		await schemaDeleteNewsTypeAndGet.validateAsync({
			id
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'select * from newstype where newstypeid=?';
	let result = await dbQuery(sqlStr, [id]);
	if (result.length >= 0) {
		sendSuccess(res, '获取新闻类型成功!', {
			data: result
		})
	} else {
		sendError(res, 500, '获取新闻类型失败，请稍后再试!')
	}
}

const getNewsByNewsTypeId = async function (req, res, next) {
	let {
		newstypeid
	} = req.query;

	if (!newstypeid) {
		sendError(res, 200, '新闻类型不能为空！');
		return;
	}

	try {
		await schemaDeleteNewsAndGet.validateAsync({
			id: newstypeid
		})
	} catch (error) {
		next(error);
		return
	}

	let sqlStr = 'select news.*,newstype.* from news inner join newstype on news.newstype_id=newstype.newstypeid where newstype_id=?'
	let result = await dbQuery(sqlStr, [newstypeid]);
	if (result.length >= 0) {
		sendSuccess(res, '获取新闻成功!', {
			data: result
		})
	} else {
		sendError(res, 500, '获取新闻失败，请稍后再试!')
	}
}

// title content picfile create_time newsTypeId
const addNews = async function (req, res, next) {
	let info = req.body;

	if (!info.title || !info.content || !info.create_time || !info.newsTypeId) {
		sendError(res, 200, '新闻标题或新闻内容或创建时间或新闻类型不能为空!');
		return;
	}

	if (!req.file) {
		sendError(res, 200, '图片不能为空！');
		return;
	}

	try {
		await schemaAddNews.validateAsync({
			title: info.title,
			content: info.content,
			create_time: info.create_time,
			newsTypeId: info.newsTypeId
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'select * from news where news_title=?'
	let result = await dbQuery(sqlStr, info.title);
	if (result.length !== 0) {
		sendError(res, 200, '新闻标题被占用，请更换其他新闻标题!');
		return;
	}
	let file = req.file.path.split('server\\')[1].replace('\\', '/').replace('\\', '/');

	let sqlStr1 = 'insert into news (news_title,news_content,news_pic_url,news_create_time,newstype_id) values (?,?,?,?,?)';
	let result1 = await dbQuery(sqlStr1, [info.title, info.content, file, info.create_time, info.newsTypeId]);
	if (result1.affectedRows == 1) {
		sendSuccess(res, '添加新闻成功!');
	} else {
		sendError(res, 500, '添加新闻失败，请稍后再试!')
	}
}

const deleteNews = async function (req, res, next) {
	let {
		id
	} = req.query;

	if (!id) {
		sendError(res, 200, 'id不能为空!');
		return;
	}

	try {
		await schemaDeleteNewsAndGet.validateAsync({
			id
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'delete from news where newsid=?'
	let result = await dbQuery(sqlStr, [id]);
	if (result.affectedRows == 1) {
		sendSuccess(res, '删除新闻成功!');
	} else {
		sendError(res, 500, '删除新闻失败，请稍后再试!')
	}
}

const getNews = async function (req, res, next) {
	let sqlStr = 'select news.*,newstype.* from news inner join newstype on news.newstype_id=newstype.newstypeid';
	let result = await dbQuery(sqlStr);
	if (result.length >= 0) {
		sendSuccess(res, '获取新闻成功!', {
			data: result
		})
	} else {
		sendError(res, 500, '获取新闻失败，请稍后再试!')
	}
}

const getNewsById = async function (req, res, next) {
	let {
		id
	} = req.query;

	if (!id) {
		sendError(res, 200, 'id不能为空！');
		return;
	}

	try {
		await schemaDeleteNewsAndGet.validateAsync({
			id
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'select * from news where newsid=?';
	let result = await dbQuery(sqlStr, [id]);
	if (result.length >= 0) {
		sendSuccess(res, '获取新闻成功!', {
			data: result
		})
	} else {
		sendError(res, 500, '获取新闻失败，请稍后再试!')
	}
}

// id title picfile newsTypeId
const editNewsNoContent = async function (req, res, next) {
	let info = req.body;

	if (!info.title || !info.newsTypeId || !info.id) {
		sendError(res, 200, '新闻标题或新闻类型或id不能为空!');
		return;
	}

	try {
		await schemaEditNews.validateAsync({
			title: info.title,
			newsTypeId: info.newsTypeId,
			id: info.id
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'select * from news where news_title=? and newsid!=?'
	let result = await dbQuery(sqlStr, [info.title, info.id]);
	if (result.length !== 0) {
		sendError(res, 200, '新闻标题被占用，请更换其他新闻标题!');
		return;
	}

	if (req.file) {
		var file = req.file.path.split('server\\')[1].replace('\\', '/').replace('\\', '/');
		let sqlStr1 = 'update news set news_title=?,news_pic_url=?,newstype_id=? where newsid=?'
		let result1 = await dbQuery(sqlStr1, [info.title, file, info.newsTypeId, info.id]);
		if (result1.affectedRows == 1) {
			sendSuccess(res, '修改新闻成功!');
		} else {
			sendError(res, 500, '修改新闻失败，请稍后再试!')
		}
	} else {
		let sqlStr1 = 'update news set news_title=?,newstype_id=? where newsid=?'
		let result1 = await dbQuery(sqlStr1, [info.title, info.newsTypeId, info.id]);
		if (result1.affectedRows == 1) {
			sendSuccess(res, '修改新闻成功!');
		} else {
			sendError(res, 500, '修改新闻失败，请稍后再试!')
		}
	}
}

// id content
const editNewsWithContent = async function (req, res, next) {
	let info = req.body;

	if (!info.content || !info.id) {
		sendError(res, 200, '新闻内容或id不能为空!');
		return;
	}

	let sqlStr = 'update news set news_content=? where newsid=?'
	let result = await dbQuery(sqlStr, [info.content, info.id]);
	if (result.affectedRows == 1) {
		sendSuccess(res, '修改新闻成功!');
	} else {
		sendError(res, 500, '修改新闻失败，请稍后再试!')
	}

}



module.exports = {
	getNewsById,
	getNewsType,
	addNewsType,
	addNews,
	editNewsType,
	deleteNewsType,
	deleteNews,
	getNews,
	editNewsNoContent,
	getNewsTypeById,
	getNewsByNewsTypeId,
	editNewsWithContent
}